<script lang="ts" setup>
import { ref,reactive ,onMounted,h,createVNode} from 'vue';
import {getUserList,register,deleteUser} from '@/api/user'
import {message,Modal} from "ant-design-vue";
import moment from "moment";
import { SearchOutlined,PlusOutlined,DeleteOutlined,ExclamationCircleOutlined } from '@ant-design/icons-vue';

let dataSource:any = reactive({source:[]})


let columns = reactive([
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
  },
  {
    title: '昵称',
    dataIndex: 'userParty',
    key: 'userParty',
  },
  {
    title: '注册时间',
    dataIndex: 'registerTime',
    key: 'registerTime',
  },{
    title: 'IP地址',
    dataIndex: 'userIp',
    key:'userIp'
  },{
    title: '用户身份',
    dataIndex: 'userType',
    key:'userType'
  },{
    title: '操作',
    key:'action'
  }
])

// 请求用户列表
let requestUserList = async () => {
  try {
    isLoading.value = true
    let res:any = await getUserList(current.value,pageSizeRef.value)
    isLoading.value = false
    console.log('用户列表',res)
    total.value = res.count
    dataSource.source = res.list
    dataSource.source.forEach((item:any) => {
      item.registerTime = moment(item.registerTime).locale('zh-cn').format('LLL')
    })
  }catch (e:any) {
    isLoading.value = false
    message.error(e.message)
  }
}


// 分页
let pageSizeOptions = ref<string[]>(['10', '20', '30', '40', '50']);
let current = ref(1);
let pageSizeRef = ref(10);
let total = ref(0);
let isLoading = ref<boolean>(false)
let showTotal = () => `共${total.value}条`

let pageChangeHandler = (page:number,pageSize:number) => {
  pageSizeRef.value = pageSize;
  current.value = page
  requestUserList()
}

let modalIsOpen = ref<boolean>(false)
const addFormState = reactive<{
  isAdmin:boolean,
  userName:string,
  userPassword:string
}>({
  isAdmin:false,
  userName:'',
  userPassword:''
})
// 单元格宽度
const labelCol = { style: { width: '150px' } };
const wrapperCol = { span: 14 };
let addIsLoading = ref<boolean>(false)
let openModale = () => {
  modalIsOpen.value = true
}
// 添加用户点击成功处理函数
let modalOkHandler = () => {
  console.log('is ok')
}

// 添加用户
let addUser = async () => {
  try {
    addIsLoading.value = true
    let isAdmin = addFormState.isAdmin == true ? 1 : 0
    let res:any = await register(addFormState.userName,addFormState.userPassword,isAdmin)
    addIsLoading.value = false
    modalIsOpen.value = false
    message.success(res.message)
    resetFormState()
    requestUserList()
  }catch (e:any) {
    addIsLoading.value = false
    message.error(e.message)
  }
}

let resetFormState = () => {
  addFormState.isAdmin = false
  addFormState.userName = ''
  addFormState.userPassword = ''
  modalIsOpen.value = false
}


// 取消添加
let cancelAdd = () => {
  resetFormState()
}

// 显示删除弹窗
const showConfirm = (record:any) => {
  Modal.confirm({
    title: '确定要删除当前用户吗? 当前操作不可逆!',
    icon: createVNode(ExclamationCircleOutlined),
    cancelText:"取消",
    okText:"删除",
    okType:"primary",
    content: createVNode('div', { style: 'color:rgba(125,122,122,1);' }, '删除之后,该用户所有资料将被删除,将无法登录,请慎重考虑!'),
    onOk() {
      try {
        deleteThisUser(record.userId)
      }catch (e:any) {
        message.error(e.message)
      }
    },
    onCancel() {

    },
    class: 'custrom-delete-confirm',
  });
};

/* 删除当前用户 */
async function deleteThisUser(userId:number|string) {
  let key = 'update'
  message.loading({content:"正在删除···",key})
  let res:any = await deleteUser(userId)
  if(res.code == 200) {
    message.success({content:"删除成功!",duration:2,key})
    requestUserList()
  }else {
    message.error({content:"删除失败!",duration:2,key})
  }
}


onMounted(() => {
  requestUserList()
})

</script>


<template>
  <div class="user-list-container">
    <div class="utils-row">
      <a-button type="primary" :icon="h(PlusOutlined)" @click="openModale">添加用户</a-button>
    </div>
    <a-spin :spinning="isLoading" tip="正在加载中···">
      <a-table
          :scroll="{ y: 'calc(60vh)' }"
          :dataSource="dataSource.source"
          :pagination="false"
          :columns="columns"
      >
        <template #bodyCell="{ column,record }">
          <template v-if="column.key=='userType' ">
            <a-tag :color="record.userType == 1 ? 'pink' : 'green' " >{{ record.userType == 1 ? '管理员' : '普通用户' }}</a-tag>
          </template>
          <!--   添加操作栏     -->
          <template v-else-if="column.key == 'action'">
            <a-button type="primary" danger @click="showConfirm(record)">
              <DeleteOutlined />删除
            </a-button>
          </template>
        </template>
      </a-table>
    </a-spin>
    <a-pagination
        v-model:current="current"
        v-model:page-size="pageSizeRef"
        :page-size-options="pageSizeOptions"
        :total="total"
        show-size-changer
        :show-total="showTotal"
        @change="pageChangeHandler"
    >
      <template #buildOptionText="props">
        <span>{{ props.value }}条/页</span>
      </template>
    </a-pagination>
    <a-modal v-model:open="modalIsOpen" title="添加新用户">
      <a-form layout="horizontal" :model="addFormState" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="用户名称">
          <a-input placeholder="用户名" v-model:value="addFormState.userName" />
        </a-form-item>
        <a-form-item label="用户密码">
          <a-input type="password" placeholder="请输入密码" v-model:value="addFormState.userPassword" />
        </a-form-item>
        <a-form-item label="是否开启管理员">
          <a-switch v-model:checked="addFormState.isAdmin" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="cancelAdd">取消</a-button>
        <a-button key="submit" :loading="addIsLoading" type="primary" @click="addUser">确认</a-button>
      </template>
    </a-modal>
  </div>
</template>


<style lang="scss" scoped>

  .ant-form {
    margin-top: 30px;
  }

.ant-pagination {
  padding: 20px 15px;
  text-align: right;
}
.utils-row {
  text-align: right;
  padding: 12px 15px;
}
</style>
